package com.huitongjy.common;


import com.huitongjy.common.generator.BatchKey;
import com.huitongjy.common.generator.ExtraKeyGenerator;
import com.huitongjy.common.generator.IKeyGenerator;
import com.huitongjy.common.generator.SimpleKeyGenerator;
import com.huitongjy.common.zookeeper.ZooKeeperWorkId;

/**
 * 作业主键Id生成器
 * workerIdBits 13 同时支持启动4096台机器,暂时没有实现自动清理,如果超过4096台,请手动清理zookeeper
 * sequenceBits 8 每毫秒支持生成128个taskId,超过等待下一毫秒
 */
public class TaskIdGenerator {
    private IKeyGenerator taskKeyGenerator;
    private IKeyGenerator examKeyGenerator;

    private TaskIdGenerator() {
        taskKeyGenerator = new SimpleKeyGenerator(13, 8, ZooKeeperWorkId.getInstanse().getWorkerId());
        examKeyGenerator = new ExtraKeyGenerator(13, 8, ZooKeeperWorkId.getInstanse().getWorkerId(),1L);
    }

    private static TaskIdGenerator INSTANCE;

    public static synchronized TaskIdGenerator getInstanse() {
        if(INSTANCE==null) {
            INSTANCE = new TaskIdGenerator();
        }
        return INSTANCE;
    }

    public Long generateKey(boolean isExam) {
        return isExam?examKeyGenerator.generateKey():taskKeyGenerator.generateKey();
    }

    public BatchKey generateKey(boolean isExam, int num) {
        return isExam?examKeyGenerator.generateKey(num):taskKeyGenerator.generateKey(num);
    }
}
